package com.audi.activity;

import java.util.List;

import lib.relay.DevListInfo;
import lib.relay.RegistRelayFunc.SignUpStatus;
import lib.relay.RelayInterface;
import lib.relay.onAuthListener;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.audi.R;
import com.audi.box.objects.Authen;
import com.audi.box.objects.LocalData;
import com.audi.box.server.TCPClient;
import com.audi.box.server.handler.HandlerFactory;
import com.audi.box.service.ConnectService;
import com.audi.handler.JSonparse;
import com.audi.handler.TrippleDes;
import com.audi.message.Connector;

//public class SigninActivity extends Activity implements onAuthListener {
public class SigninActivity extends Activity implements onAuthListener { 
	private Context mContext;
	private EditText edtEmailSignIn, edtPasswordSignIn;
	private ImageButton btnSignin;
	private TextView txtForgotPasswordSignIn;
	private TextView txtSignup;
	private EditText etip, etport;
	private Button btnreload;
	private ProgressDialog m_DlgProgress = null;
	private boolean bIsRelayLogin = false;
	private boolean bIsLogoutWhenClose = false;
	private static String TAG_LOGIN = "[Login]";
	public static TCPClient mTcpClient;
	private ProgressDialog pDialog;
	private Boolean istcpsuccess = false;
	private String Tag1 = "SigninActivity";
	private String Tag2 = "Loginactivity";
	ProgressDialog progress;

	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_signin);

		if (Connector.SEND_MODE == Connector.iTH_Offline) {
			HandlerFactory.create(this);
		} else {
			new RelayInterface();
			RelayInterface.SetInterface(this);
			RelayInterface.m_onAuthListener = this;
		}

		initView();
		initData();
		initListener();
//		new ConnecttoServer().execute("");
//		connect();
		
		btnreload.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(SigninActivity.this, "Connecting...", Toast.LENGTH_LONG).show();
				connect();
			}
		});
	}
	private void connect()
	{	
		LocalData.strIP=etip.getText().toString();
		LocalData.strport=Integer.parseInt(etport.getText().toString());
		try {
			Log.d(LocalData.TAG_SERVICE,"try to start");
			try{
//			startService(new Intent(this, ConnectService.class));
				Log.d(LocalData.TAG_SERVICE,"inside try");
				startService(new Intent(SigninActivity.this, ConnectService.class));
			}
			catch (Exception e)
			{
				Log.e(LocalData.TAG_SERVICE,""+e);
			}
		}
		catch(Exception e)
		{
			Log.e(LocalData.TAG_SERVICE,"fail to start" + e);
		}
			if (LocalData.isConnectsuccess==true)
			{
				btnreload.setVisibility(View.GONE);
			}
			else btnreload.setVisibility(View.VISIBLE);
	}
	private void initView() {
		edtEmailSignIn = (EditText) findViewById(R.id.edt_email);
		edtPasswordSignIn = (EditText) findViewById(R.id.edt_password);
		btnSignin = (ImageButton) findViewById(R.id.btn_signin);
		txtForgotPasswordSignIn = (TextView) findViewById(R.id.txt_forgot_password);
		txtSignup = (TextView) findViewById(R.id.txt_sign_up);
		txtSignup.setBackgroundResource(Color.TRANSPARENT);
		etip = (EditText) findViewById(R.id.edtIP);
		etport = (EditText) findViewById(R.id.edtPort);
		//set IP
		etip.setText("192.168.3.101");
		btnreload = (Button) findViewById(R.id.btnreload);
		// SQLiteAsusNewHelper item = new SQLiteAsusNewHelper(this);
		// if (item.getListDeviceAll().size() < 1) {
		// DBHelper.addDataTest(item);
		// }
		edtEmailSignIn.setText("Son");
		edtPasswordSignIn.setText("123");
	}

	private void initData() {
		mContext = SigninActivity.this;
	}

	private void initListener() {
		btnSignin.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				signIn();
			}
		});
		txtForgotPasswordSignIn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Toast.makeText(mContext, "Run Forgot password",
						Toast.LENGTH_SHORT).show();
			}
		});
		SpannableStringBuilder text = new SpannableStringBuilder(
				getString(R.string.new_member));
		ClickableSpan clickableSpan = new ClickableSpan() {
			@Override
			public void onClick(View view) {
				view.setBackgroundResource(Color.TRANSPARENT);
				startActivity(new Intent(SigninActivity.this,
						PreSignActivity.class));
			}

			@Override
			public void updateDrawState(final TextPaint textPaint) {

				textPaint.setColor(SigninActivity.this.getResources().getColor(
						R.color.white));
				textPaint.setUnderlineText(true);
			}
		};
		text.setSpan(clickableSpan, 11, 18, 0);

		text.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 11, 18, 0);
		txtSignup.setMovementMethod(LinkMovementMethod.getInstance());

		txtSignup.setText(text);
	}

	private void signIn() {
		if (TextUtils.isEmpty(edtEmailSignIn.getText().toString().trim())) {
			Toast.makeText(mContext, "Please input email", Toast.LENGTH_SHORT)
					.show();
			return;
		}
//		if (!Patterns.EMAIL_ADDRESS.matcher(
//				edtEmailSignIn.getText().toString().trim()).matches()) {
//			Toast.makeText(mContext, "Email invalid", Toast.LENGTH_SHORT)
//					.show();
//			return;
//		}
		if (TextUtils.isEmpty(edtPasswordSignIn.getText().toString().trim())) {
			Toast.makeText(mContext, "Please input password",
					Toast.LENGTH_SHORT).show();
			return;
		}
		if (Connector.SEND_MODE == Connector.iTH_Offline) {
			try{
			 Loader aslogin = new Loader();
			 aslogin.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
			}
			catch(Exception e)
			{
				Log.e(Tag2,"cant start asycn"+e);
			}
		} else {
			CreateProgressDialog("Login relay...");
			RelayInterface.GetRelaySAuth(edtEmailSignIn.getText().toString(),
					edtPasswordSignIn.getText().toString());
		}
		LocalData.strIP = etip.getText().toString();
		LocalData.strport = Integer.parseInt(etport.getText().toString());
	}

	private void CreateWarningDialog(String strMessage) {
		AlertDialog.Builder m_Builder = new AlertDialog.Builder(this);
		m_Builder.setTitle(null);
		m_Builder.setMessage(strMessage);
		m_Builder.setPositiveButton("Ok",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
					}
				});
		m_Builder.create().show();
	}

	private void CreateProgressDialog(String strMessage) {
		m_DlgProgress = new ProgressDialog(this);
		m_DlgProgress.setTitle(null);
		m_DlgProgress.setMessage(strMessage);
		m_DlgProgress.setIndeterminate(true);
		m_DlgProgress.setCancelable(true);
		m_DlgProgress.show();
	}

	private void DestroyProgressDialog() {
		if (m_DlgProgress != null)
			m_DlgProgress.dismiss();
	}

	@Override
	public void GetAuthFinished(boolean bValue) {
		if (bValue == true) {
			Log.d(TAG_LOGIN, "[SigninActivity.java] Login Relay successfully.");
			int iPortNum = 8;
			String[][] port = new String[2][iPortNum];
			port[0] = new String[] { "5050", "5066", "5067", "5069", "16120",
					"16121", "16122", "7777" };
			port[1] = new String[] { "5050", "5066", "5067", "5069", "16120",
					"16121", "16122", "7777" };
			RelayInterface.RelayInit(port, iPortNum);
		} else {
			runOnUiThread(new Runnable() {
				public void run() {
					DestroyProgressDialog();
					Log.d(TAG_LOGIN,
							"[SigninActivity.java] Failed to login Relay.");
					CreateWarningDialog("Failed to login Relay.");
				}
			});
		}
	}

	@Override
	public void ListProfileFinished(List<DevListInfo> relay_list) {

	}

	@Override
	public void LogoutFinished(final boolean bValue) {
		runOnUiThread(new Runnable() {
			public void run() {
				DestroyProgressDialog();
				if (bIsLogoutWhenClose == false) {
					if (bValue == true) {
						Log.d(TAG_LOGIN,
								"[MainActivity.java] Logout Relay successfully.");
						bIsRelayLogin = false;
						CreateWarningDialog("Logout Relay successfully.");
					} else {
						Log.d(TAG_LOGIN,
								"[MainActivity.java] Failed to Logout Relay.");
						CreateWarningDialog("Failed to Logout Relay.");
					}
				} else {
					bIsRelayLogin = false;
					onBackPressed();
				}
			}
		});
	}

	@Override
	public void CBInit(final boolean bValue) {
		runOnUiThread(new Runnable() {
			public void run() {
				// DestroyProgressDialog();
				// if (bValue == true) {
				// bIsRelayLogin = true;
				// Log.d(TAG_LOGIN,
				// "[MainActivity.java] Initialize Relay successfully.");
				// Preference preference = new Preference(SigninActivity.this);
				// preference.setMyMember(edtEmailSignIn.getText().toString());
				// startActivity(new Intent(mContext, TutorialActivity.class));
				// // startActivity(new Intent(mContext,
				// // HomeControlActivity.class));
				// finish();
				// } else {
				// Log.d(TAG_LOGIN,
				// "[MainActivity.java] Failed to Initialize Relay.");
				// CreateWarningDialog("Failed to Initialize Relay.");
				// }
			}
		});
	}

	@Override
	public void CBMakeCall(boolean bValue) {

	}

	@Override
	public void CBHangUp(final boolean bValue) {
		runOnUiThread(new Runnable() {
			public void run() {
				DestroyProgressDialog();
				if (bValue == true) {
					Log.d(TAG_LOGIN,
							"[MainActivity.java] Success to hangup relay");
					CreateWarningDialog("[MainActivity.java] Success to hangup relay");
				} else {
					Log.d(TAG_LOGIN,
							"[MainActivity.java] Failed to hangup relay");
					CreateWarningDialog("[MainActivity.java] Failed to hangup relay");

				}
			}
		});
	}

	@Override
	public void CBDeInit(boolean bValue) {
		if (bValue == true) {
			Log.d(TAG_LOGIN, "[MainActivity.java] DeInit Relay successfully.");
			RelayInterface.LogoutRelayS();
		} else {
			runOnUiThread(new Runnable() {
				public void run() {
					DestroyProgressDialog();
					Log.d(TAG_LOGIN,
							"[MainActivity.java] Failed to DeInit Relay.");
					CreateWarningDialog("Failed to DeInit Relay");
				}
			});

		}
	}

	@Override
	public void CBClientSocket(String CBString) {

	}

	@Override
	public void onBackPressed() {
		// [relay]
		if (bIsRelayLogin == true) {
			CreateProgressDialog("Logout relay...");
			bIsLogoutWhenClose = true;
			RelayInterface.RelayDeInit();
		} else {
			super.onBackPressed();
		}
	}

	@Override
	public void GetSignUp(final SignUpStatus mSignUpStatus) {

	}

//	private void loadlogin()
//	{	
//		progress = ProgressDialog.show(SigninActivity.this, "Vui lòng chờ",
//			    "Đang đăng nhập", true); 
//		
//		new Thread(new Runnable() { 
//			  @Override 
//			  public void run() 
//			  { 
//				  try {
//						if (LocalData.isConnectsuccess == true) {
//							Log.d(Tag2, "Send-1");
//							JSONObject jslogin = new JSONObject();
//							JSONObject jslogin2 = new JSONObject();
//							try {
//								jslogin2.put("email", edtEmailSignIn.getText().toString());
//								jslogin2.put("password", edtPasswordSignIn.getText()
//										.toString());
//								jslogin.put("tag","login");
//								jslogin.put("strjson",jslogin2);
//								Log.d(Tag2, "Put Json-2");
//							} catch (JSONException e) {						
//								Log.e(Tag2, "JSON failed-3" + e);
//							}
//							ConnectService.mmTcpClient.sendMessage(jslogin.toString());
//							
//							model =  JSonparse.getauthen(LocalData.strreceiver);
//							Log.d(Tag2, "JsonString: " + jslogin.toString());						
//						}
//						else {
//							Log.e(Tag2, "Connect not success-4" + LocalData.isConnectsuccess);
//						}
//					} catch (Exception e) {
//						Log.e(Tag2, "Fail parse Json-5" + e);
//					}
//			    // do the thing that takes a long time 
//			 
//			    runOnUiThread(new Runnable() {
//			      @Override 
//			      public void run() 
//			      { 
//			    	  try{long startTime = System.currentTimeMillis();
//			    	  Log.i(LocalData.TAG_LOGIN,"trước khi vào while");
//			    	  int i=0;
//			  		while (LocalData.islogin==true||(System.currentTimeMillis()-startTime)<10000)
//			  		{
//			  			Log.i(LocalData.TAG_LOGIN,""+i +"  Time: "+System.currentTimeMillis());
//			  			i++;
//			  		}
//			    	  }
//			    	  catch(Exception e)
//			    	  {
//			    		  Log.e(LocalData.TAG_LOGIN,""+e);
//			    	  }
//			        progress.dismiss(); 
//			    	if (LocalData.islogin==true)
//					{	
//						Toast.makeText(SigninActivity.this, "Đăng nhập thành công", Toast.LENGTH_SHORT).show();
//						Intent inhctr = new Intent(SigninActivity.this,HomeControlActivity.class);
//						startActivity(inhctr);
//					}
//					else {alertmess("Không thể kết nối đến máy chủ");}
//			      } 
//			    }); 
//			  } 
//			}).start(); 
//	
//	}

	/**
	 * Connect to server task
	 */

//	class ConnecttoServer extends AsyncTask<String, String, TCPClient> {
//
//		/**
//		 * Before starting background thread Show Progress Dialog
//		 * */
//		@Override
//		protected void onPreExecute() {
//			super.onPreExecute();
//			pDialog = new ProgressDialog(SigninActivity.this);
//			pDialog.setMessage("Connect to Server");
//			pDialog.setIndeterminate(false);
//			pDialog.setCancelable(false);
//			pDialog.show();
//		}
//
//		protected TCPClient doInBackground(String... message) {
//			// Building Parameters
//			try {
//				try {
//					mTcpClient = new TCPClient(
//							new TCPClient.OnMessageReceived() {
//								@Override
//								// here the messageReceived method is
//								// implemented
//								public void messageReceived(String message) {
//									// this method calls the onProgressUpdate
//									Log.d(Tag1,
//											"Services started - in asycn task- receiver message - 2");
//									publishProgress(message);
//								}
//							});
//					Log.d(Tag1, "Services started - in asycn task pre run- 3");
////					mTcpClient.run(LocalData.strIP, 44444);
////					mTcpClient.run("172.16.10.37", 44444);
//					mTcpClient.run("192.168.11.110", 44444);
//					if (LocalData.isConnectsuccess == false) {
//						publishProgress("Connect Failed");
//					}
//					Log.d(Tag1, "Services started - in asycn task- 4");
//				} catch (Exception e) {
//					Log.e(Tag1, "" + e);
//				}
//			} catch (Exception e) {
//				Log.e(Tag1, "fail to start" + e);
//			}
//
//			// Kiểm tra kết quả đăng nhập
//
//			return null;
//		}
//
//		/**
//		 * After completing background task Dismiss the progress dialog
//		 * **/
//		@Override
//		protected void onProgressUpdate(final String... values) {
//			super.onProgressUpdate(values);
//			Log.i(Tag1, "Onprogressupdate" + values[0]);
//			LocalData.strreceiver = values[0];
//			pDialog.dismiss();
//			OJResponsive result = new OJResponsive();
//			if (LocalData.isConnectsuccess ==false)
//			{
//				alertfailmess(getString(R.string.err_connecttion));
//			}
//			else {
//				try{
//					Log.d(LocalData.TAG_SERVICE,"try to start");
////					startService(new Intent(SigninActivity.this, ConnectService.class));
//					}
//					catch(Exception e)
//					{
//						Log.e(Tag1,"Failed when start service"+e);
//					}
//				Toast.makeText(SigninActivity.this, getString(R.string.connect_success)+LocalData.isConnectsuccess,
//						Toast.LENGTH_SHORT).show();
//				
//			}
//		}
//
//	}
/**
 * 
 * Login task
 *
 */
	void alertmess(String mess) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(mess).setTitle("Thông báo").setCancelable(false)
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						return;
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}
	void alertfailmess(String mess) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(mess).setTitle("Thông báo").setCancelable(false)
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						finish();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}
/*
 * 
 * 
 * 
 * 
 */
	
	private Authen model = null;

	public class Loader extends AsyncTask<Void, Void, Authen> {
		@Override
		protected void onPreExecute() {	
			super.onPreExecute();
			pDialog = new ProgressDialog(SigninActivity.this);
			pDialog.setMessage("Logging in");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
			Log.d(Tag2, "pdialog show");		
		}

		@Override
		protected Authen doInBackground(Void... arg0) {

			JSONObject jslogin = new JSONObject();
			JSONObject jslogin2 = new JSONObject();
			
			Log.d(Tag2, "Doinbackground");
			try {
				if (LocalData.isConnectsuccess == true) {
					Log.d(Tag2, "Send-1");
					
					try {
						
						jslogin2.put(LocalData.TAG_USERNAME, edtEmailSignIn.getText().toString());
						String ecryptpass = TrippleDes.encrypt(edtPasswordSignIn.getText()
								.toString());
						jslogin2.put(LocalData.TAG_PASS, ecryptpass);
//						jslogin2.put(LocalData.TAG_PASS, edtPasswordSignIn.getText()
//								.toString());
						jslogin.put("tag","login");
						jslogin.put("strjson",jslogin2);
						Log.d(Tag2, "Put Json-2");
						Log.i(Tag2, "JsonString: " + jslogin.toString());
					} catch (JSONException e) {						
						Log.e(Tag2, "JSON failed-3" + e);
					}
					ConnectService.mmTcpClient.sendMessage(jslogin.toString());
										
					Log.d(Tag2, "JsonString: " + jslogin.toString());						
				}
				else {
					Log.e(Tag2, "Connect not success-4" + LocalData.isConnectsuccess);
				}
			} catch (Exception e) {
				Log.e(Tag2, "Fail parse Json-5" + e);
			}
			long startTime = System.currentTimeMillis();
			try {
				Log.d(Tag2, "Trước while" + LocalData.islogin );				
				while ((System.currentTimeMillis()-startTime)<5000)
	  		{		if (LocalData.islogin == true ) 
	  				{LocalData.usename =edtEmailSignIn.getText().toString();
	  				break;
	  				}
	  		}
				}
			catch(Exception e)
			{
				Log.e(Tag2,""+e);
			}
			Log.d(Tag2, "end of doinbackground");	
			
			model =  JSonparse.getauthen(LocalData.strreceiver);
				return model;
		}

		@Override
		protected void onPostExecute(final Authen model) {
			Log.i("TESTTROLW", "TESTTROLW: 9");
			super.onPostExecute(model);// sfsmdf
			pDialog.dismiss();
			try {
				Log.d(Tag2,"in postexecute -1 " + LocalData.islogin);
				Log.d(Tag2,"Info " + model.getSuccess() + "---" + model.getTag() + " | "+ model.getUser_group());
				if (LocalData.islogin==true) {
//					if (!model.getSuccess())
//					{
//						alertmess("		Đăng nhập thất bại" +model.getSuccess() );
//					}
//					else {
					LocalData.usergroup = model.getUser_group();
					Log.i(LocalData.TAG_LOGIN,"username: "+ model.getUser_name() + "--usergroup: "+ model.getUser_group());
						Log.d(Tag2, "On pregress update - 5");	
						Toast.makeText(SigninActivity.this, "Đăng nhập thành công", Toast.LENGTH_SHORT).show();
						Intent inhctr = new Intent(SigninActivity.this,HomeControlActivity.class);
						inhctr.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						inhctr
								.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
						startActivity(inhctr);
						finish();
//					}
				} else {
					alertmess("Đăng nhập thất bại \nVui lòng kiểm tra Tên và Mật khẩu đăng nhập");
					}				
			} catch (Exception e) {
				e.printStackTrace();
				alertmess("Đăng nhập thất bại-3");
				Log.d(Tag2,"in postexecute -2 "+e);
			}
		}
		
	}
}